package cc.ttiot.service.dataCollection.serial.impl;

import cc.ttiot.service.dataCollection.serial.SerialCollection;
import cc.ttiot.service.dataCollection.serial.SerialPortWrapperImpl;
import cc.ttiot.service.dataCollection.serial.protocol.modbusRtu.ModbusRtuMaster;
import cc.ttiot.service.dataCollection.serial.protocol.modbusRtu.ModbusRtuUtils;
import com.pi4j.io.serial.SerialConfig;
import com.serotonin.modbus4j.exception.ModbusInitException;


import static cc.ttiot.service.dataCollection.serial.protocol.modbusRtu.ModbusRtuSlave.SLAVE_ID_OF_VIBRATION_AND_TEMPERATURE_SENSOR;


/**
 * @Description: 最初选用的一款基于modbusRTU协议，通过RS-485通信的温振传感器（可以测三轴振动）
 * @Author :
 * @Version :
 * @Date :
 */
public class TemperatureAndVibrationCollection implements SerialCollection {
    //ModbusRTUMaster实例
    private ModbusRtuMaster modbusRTUMaster;

    public TemperatureAndVibrationCollection() {
        super();
    }

    //创建并初始化modbus(串口以默认配置)

    /**
     * 默认配置:
     * "--device (device-path)"                   [DEFAULT: /dev/ttyAMA0]
     * "--baud (baud-rate)"                       [DEFAULT: 9600]
     * "--data-bits (5|6|7|8)"                    [DEFAULT: 8]
     * "--parity (none|odd|even)"                 [DEFAULT: none]
     * "--stop-bits (1|2)"                        [DEFAULT: 1]
     * "--flow-control (none|hardware|software)"  [DEFAULT: none]
     */
    public void init() throws ModbusInitException {
        this.modbusRTUMaster = ModbusRtuUtils.createModbusRTUMaster(new SerialPortWrapperImpl());
        System.out.println("Modbus初始化完成，开始读取保持寄存器");
    }

    //创建并初始化modbus(串口以指定serialConfig配置)
    public void init(SerialConfig serialConfig) throws ModbusInitException {
        this.modbusRTUMaster = ModbusRtuUtils.createModbusRTUMaster(new SerialPortWrapperImpl(serialConfig));
        System.out.println("Modbus初始化完成，开始读取保持寄存器");
    }

    //采集单次数据
    public short[] collect(){
        //该传感器从机编号为1，读地址为0x00-0x03的保持寄存器
        //注意读出来的值都是实际值的十倍
        return modbusRTUMaster.readHoldingRegistersTest(SLAVE_ID_OF_VIBRATION_AND_TEMPERATURE_SENSOR, 0, 4);
    }

    //关闭modbusRTU及其串口
    public void close() {
        if (modbusRTUMaster != null) {
            modbusRTUMaster.close();
            System.out.println("serial.close()执行完毕");
        }
    }
}
